'''
  @Description      
  @auther         leizi
  @create          2020-02-16 15:41
'''
import os, re
from wsgiref.validate import validator
from until.log import LOG


class GetFPs():
    def __init__(self, devices_name, packname):
        self.devices_name = devices_name
        self.packlname = packname

    def getfps(self):
        fps = 0
        try:
            cmd = "adb -s %s shell dumpsys gfxinfo %s" % (self.devices_name,
                                                          self.packlname)
            result = os.popen(cmd).read().strip()
            frames = [x for x in result.split('\n') if validator(x)]
            frame_count = len(frames)
            jank_count = 0
            vsync_overtime = 0
            render_time = 0
            for frame in frames:
                time_block = re.split(r'\s+', frame.strip())
                if len(time_block) == 3:
                    try:
                        render_time = float(time_block[0]) + float(time_block[1]) + float(time_block[2])
                    except Exception as e:
                        render_time = 0
                if render_time > 16.67:
                    jank_count += 1
                    if render_time % 16.67 == 0:
                        vsync_overtime += int(render_time / 16.67) - 1
                    else:
                        vsync_overtime += int(render_time / 16.67)
            fps = int(frame_count * 60 / (frame_count + vsync_overtime))
        except Exception as e:
            LOG.log("获取FPS失败，原因：%s" % str(e))
        return fps
